package org.apache.ibatis.common.type;

import java.sql.*;
import java.time.Instant;

/**
 * @Name InstantTypeHandler
 * @Description: [SQL Timestamp -> JAVA Instant] 类型处理器
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-05-10 18:01:13
 **/
public class InstantTypeHandler extends BaseTypeHandler<Instant> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Instant parameter, JdbcType jdbcType) throws SQLException {
        ps.setTimestamp(i, Timestamp.from(parameter));
    }

    @Override
    public Instant getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnName);
        return getInstant(timestamp);
    }

    @Override
    public Instant getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnIndex);
        return getInstant(timestamp);
    }

    @Override
    public Instant getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp timestamp = cs.getTimestamp(columnIndex);
        return getInstant(timestamp);
    }

    private Instant getInstant(Timestamp timestamp) {
        if (timestamp != null) return timestamp.toInstant();
        return null;
    }
}

